package com.yxn.cloud.order.listener;

import com.rabbitmq.client.Channel;
import com.yxn.cloud.order.entity.OrderEntity;
import com.yxn.cloud.order.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author lisw
 * @create 2021/8/15 21:18
 */
@Service
@RabbitListener(queues = "order.release.order.queue")
public class OrderListener {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    OrderService orderService;

    @RabbitHandler
    public void createOrder(OrderEntity orderEntity, Message message, Channel channel) {
        try {
            logger.info("订单开始自动关单，orderEntity:{}", orderEntity);
            orderService.closeOrder(orderEntity);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            rejectMessage(message, channel);
        }
    }

    private void rejectMessage(Message message, Channel channel) {
        try {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        } catch (IOException e) {
            logger.info("消息拒绝异常，e:{}", e);
        }
    }
}
